#!/usr/bin/env python
#-*- coding: utf-8 -*-
#__author__:vincentlc
#time: 16/4/10 : 16:48

"""
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example:
Given binary tree {3,9,20,#,#,15,7},
    3
   / \
  9  20
    /  \
   15   7
return its bottom-up level order traversal as:
[
  [15,7],
  [9,20],
  [3]
]
这道题主要有几个问题吧,
1.怎么递归调用
2.如何保存一层数据(广度优先搜索)
"""

# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution(object):
    def __init__(self):
        self.result = []
        self.levelResult = []
        self.child_box = []
        self.tmp_box = []

    def levelOrderBottom(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if root == None:
            return []
        else:
            self.tmp_box.append(root)
            self.TraversalTree()
            a = self.result
            return a

    def TraversalTree(self):
        while True:
            self.child_box = []
            self.levelResult = []
            for current in self.tmp_box:
                if current.left != None:
                    self.child_box.append(current.left)
                if current.right != None:
                    self.child_box.append(current.right)
                self.levelResult.append(current.val)

            if len(self.child_box)>0:
                self.tmp_box = self.child_box
                # self.result.append(self.levelResult)
                self.result.insert(0,self.levelResult)
            else:
                self.result.insert(0,self.levelResult)
                return
test1 = TreeNode(1)
test1.left= TreeNode(2)
test1.right = TreeNode(3)
test1.left.left= TreeNode(4)
test1.left.right= TreeNode(5)
a = Solution()
print (a.levelOrderBottom(test1))







